package binaryTree;

import java.util.ArrayList;

/*
 *@description 二叉树展开为链表
 *@author hkfan
 *@version 1.0
 *@create 2025/6/16 15:36
 */
public class LeetCode_114 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public void flatten(TreeNode root) {
        //1. 中序遍历记录
        ArrayList<TreeNode> list = new ArrayList<>();
        recordList(root,list);
        //2. 修改指针指向
        int i=0;
        for (; i < list.size()-1; i++) {
            list.get(i).left=null;
            list.get(i).right=list.get(i+1);
        }
        if (i!=0){
            list.get(list.size()-1).left=null;
            list.get(list.size()-1).right=null;
        }

    }

    private void recordList(TreeNode root, ArrayList<TreeNode> list) {
        if (root!=null){
            list.add(root);
            recordList(root.left,list);
            recordList(root.right,list);
        }
    }
}
